<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>发起工单</span>
      </div>
      <div class="content" v-if="formOpen">
        <parser v-if="formData.formRef" :key="new Date().getTime()" :form-conf="formData" :isDetail="false" @submit="submit" @save="saveForm" @cancel="cancelForm" ref="parser" @getData="getData" />
        <CptSelfForm v-else ref="CptSelfForm" :formDataCfg="getSelfFormData(formData)" @submit="submit" @save="saveForm" @cancel="cancelForm"></CptSelfForm>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getProcessForm, startSave, detailProcess } from '@/api/workflow/process'
import { complete, instanceCancel,reqUpdateWorkStatus} from '@/api/workflow/task'
import Parser from '@/utils/generator/parser'
import CptSelfForm from '@/components/CptSelfForm'
import store from "@/store";
import { getConstForCurTaskOperateBtnConfig } from "@/utils/dict/cfg";

export default {
  name: 'WorkStart',
  components: {
    Parser,
    CptSelfForm
  },
  data() {
    return {
      definitionId: null,
      deployId: null,
      procInsId: null,
      formOpen: false,
      formData: {},
      taskId: null,
      curTaskOperateBtnConfig: getConstForCurTaskOperateBtnConfig(),
    }
  },
  created() {
    this.initData();
    this.initSelfFormApplyData()
  },
  methods: {
    initData() {
      this.deployId = this.$route.params && this.$route.params.deployId;
      this.definitionId = this.$route.query && this.$route.query.definitionId;
      this.procInsId = this.$route.query && this.$route.query.procInsId;
      this.taskId = this.$route.query && this.$route.query.taskId
      getProcessForm({
        definitionId: this.definitionId,
        deployId: this.deployId,
        procInsId: this.procInsId
      }).then(res => {
        if (res.data) {
          this.formData = res.data;
          this.formOpen = true
        }
      })
      detailProcess({ 'procInsId': this.procInsId, 'taskId': this.taskId }).then(res => {
        const data = res.data;
        let selfFormRef = this.$refs['CptSelfForm']
        if (selfFormRef) {
          selfFormRef.setTaskProcessDetail(data)
          // 办理操作按钮权限
          this.curTaskOperateBtnConfig = selfFormRef.getCurTaskOperateBtnConfig()
        }
      })
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    submit(data) {
      if (data && this.definitionId) {
        this.inflateValData(data)
        // 审批确认操作，审批意见是否必填
        if (this.curTaskOperateBtnConfig.curTaskCommentRequired && (data === null || data.taskForm === null || data.taskForm.comment === null || data.taskForm.comment === '')) {
          this.$alert('请在申请备注中输入申请备注信息', "系统提示");
          return
        }
        // 启动流程并将表单数据加入流程变量
        // startProcess(this.definitionId, JSON.stringify(data.valData)).then(res => {
        //   this.$modal.msgSuccess(res.msg);
        //   this.$tab.closeOpenPage({
        //     path: '/work/own'
        //   })
        // })
        let taskForm = {
          comment: (data.taskForm && data.taskForm.comment && data.taskForm.comment.length) ? data.taskForm.comment : '   ', // 意见内容
          procInsId: this.procInsId, // 流程实例编号
          taskId: this.taskId,// 流程任务编号
          copyUserIds: "", // 抄送人Id
          vars: "",
          targetKey: "",
          variables: data.valData
        }
        complete(taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          reqUpdateWorkStatus(
            {
              businessKey: this.$route.query['cur_businessKey'],
              businessStatus: "2",
              taskId: this.taskId
            }
          ).then((res)=>{
            this.$tab.closeOpenPage({
              path: '/work/own'
            })
          })  
        }).catch(error => {
          console.error(error)
        })
      }
    },
    /**
     * 发起审批，提交用户信息数据
     * @author gaogm
     */
    inflateValData(data) {
      if (data && data.valData) {
        let user = this.$store.state.user
        let role = '';
        if (user && user.roles) {
          role = user.roles[0]
        }
        data.valData.curRoleCode = role
      }
    },
    /**
     * 发起暂存，提交标记信息
     * @author gaogm
     */
    inflateValDataForStaging(data) {
      if (data && data.valData) {
        data.valData.curTaskStaging = 'Y'
      }
    },
    // 暂存
    saveForm(data) {
      if (data && this.taskId) {
        this.inflateValDataForStaging(data)
        let taskForm = {
          comment: (data.taskForm && data.taskForm.comment && data.taskForm.comment.length) ? data.taskForm.comment : '', // 意见内容
          procInsId: this.procInsId, // 流程实例编号
          taskId: this.taskId,// 流程任务编号
          copyUserIds: "", // 抄送人Id
          vars: "",
          targetKey: "",
          variables: data.valData
        }
        startSave(taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          reqUpdateWorkStatus(
            {
              businessKey:this.$route.query['cur_businessKey'],
              businessStatus:"1",
              taskId:this.taskId
            }
          ).then((res)=>{
            this.$tab.closeOpenPage({
              path: '/work/own'
            })
          })
        }).catch(error => {
          console.error(error)
        })
      }
    },
    cancelForm(data) {
      if (data && this.taskId) {
        let taskForm = {
          comment: "   ", // 意见内容
          procInsId: this.procInsId, // 流程实例编号
          taskId: this.taskId,// 流程任务编号
          copyUserIds: "", // 抄送人Id
          vars: "",
          targetKey: "",
          variables: data.valData
        }
        instanceCancel(taskForm).then(res => {
          this.$modal.msgSuccess(res.msg);
          reqUpdateWorkStatus(
            {
              businessKey:this.$route.query['cur_businessKey'],
              businessStatus:"5",
              taskId:this.taskId
            }
          ).then((res)=>{
            this.$tab.closeOpenPage({
              path: '/work/own'
            })
          })    
        });
      }
    },
    getSelfFormData(fData) {
      return {
        'formContent': fData.formContent,
        'formData': fData.variables,
        'optionData': {}
      }
    },
    initSelfFormApplyData() {
      if (this.$route.query) {
        let selfFormInitData = {
          'cur_category': this.$route.query.cur_category,
          'cur_subcategory': this.$route.query.cur_subcategory,
          'cur_businessKey': this.$route.query.cur_businessKey,
        }
        console.log('selfFormInitData', selfFormInitData)
        store.dispatch("selfForm/initFormData", selfFormInitData).then(() => {
          console.log('initFormData')
        }).catch(error => { console.error(error) });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
}
</style>
